package com.tencent.cloud.iov.util;

import android.util.Log;

import com.tencent.cloud.iov.util.crypt.CustomSRPClient;
import com.tencent.cloud.iov.util.crypt.SRPData;

import org.spongycastle.crypto.CryptoException;
import org.spongycastle.crypto.digests.SHA256Digest;
import org.spongycastle.crypto.params.SRP6GroupParameters;

import java.math.BigInteger;
import java.security.SecureRandom;


public class SRPUtils {

    private static final String TAG = SRPUtils.class.getSimpleName();

    public static final String SRP_SALT = "srp_salt";

    public static final String SRP_GROUP = "srp_group";

    public static final String SRP_SERVER_PUBLIC_KEY = "srp_server_public_key";

    public static CustomSRPClient getCustomSRPClient() {
        return new CustomSRPClient();
    }

    /**
     * @param data  要加密的数据
     * @param salt  bcrypt用的盐
     * @param group srp协议使用的group
     */
    public static String encryptData(CustomSRPClient srpClient, String data,
                                     String salt, String group) {
        SRP6GroupParameters groupParameters = SRPData.getGroupParameters(group);
        srpClient.init(groupParameters, new SHA256Digest(), new SecureRandom());
        BigInteger verifier = groupParameters.getG().modPow(srpClient.generateClientCredentials
                (data, salt), groupParameters.getN());
        return verifier.toString();
    }

    /**
     * @param data  要加密的数据
     * @param salt  bcrypt用的盐
     * @param group srp协议使用的group
     */
    public static String encryptData(String data, String salt, String group) {
        CustomSRPClient srpClient = new CustomSRPClient();
        return encryptData(srpClient, data, salt, group);
    }

    public static String[] generateAuthenticateInfo(CustomSRPClient srpClient, String data,
                                                    String salt, String group,
                                                    String publicKey) {
        srpClient.init(SRPData.getGroupParameters(group), new SHA256Digest(), new SecureRandom());
        BigInteger generateA = srpClient.generateA();
        srpClient.generateClientCredentials(data, salt);
        try {
            srpClient.calculateSecret(new BigInteger(publicKey));
            BigInteger evidenceMessage = srpClient.calculateClientEvidenceMessage();
            return new String[]{generateA.toString(), evidenceMessage.toString()};
        } catch (CryptoException e) {
            Log.e(TAG, "generate authenticate info failed", e);
            return null;
        }
    }

    /**
     * 验证置信证明
     *
     * @param srpClient
     * @param evidenceMessage
     * @return
     */
    public static boolean verifyEvidenceMessage(CustomSRPClient srpClient, String evidenceMessage) {
        try {
            return srpClient.verifyServerEvidenceMessage(new BigInteger(evidenceMessage));
        } catch (CryptoException e) {
            e.printStackTrace();
            return false;
        }
    }

}
